using System;
using System.Collections.Generic;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Controls.Primitives;

namespace MyPublisher.Windows.Controls
{
    public class DropDownButton : ToggleButton
    {
        public DropDownButton()
        {
            Binding binding = new Binding("DropDown.IsOpen");
            binding.Source = this;
            this.SetBinding(IsCheckedProperty, binding);
        }


        private ContextMenu _dropDownMenu;
        public ContextMenu DropDownMenu
        {
            get
            {
                this.SortContextMenuItemsByHeader(this._dropDownMenu.Items);
                return this._dropDownMenu;
            }
            set
            {
                this._dropDownMenu = value;
            }
        }

        public void PerformClick()
        {
            DropDownMenu.IsOpen = true;
        }

        protected override void OnClick()
        {
            if (DropDownMenu != null)
            {
                DropDownMenu.PlacementTarget = this;
                DropDownMenu.Placement = PlacementMode.Bottom;
                DropDownMenu.IsOpen = true;
            }
        }

        private void SortContextMenuItemsByHeader(ItemCollection items)
        {
            List<MenuItem> itemList = new List<MenuItem>();
            foreach (MenuItem item in items)
            {
                itemList.Add(item);
                if (item.Items.Count > 0)
                {
                    this.SortContextMenuItemsByHeader(item.Items);
                }
            }

            itemList.Sort((x, y) => { return string.Compare(x.Header.ToString(), y.Header.ToString()); });

            items.Clear();

            foreach (MenuItem item in itemList)
            {
                items.Add(item);
            }

        }
    }


}
